package com.example.config;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

public class WatchCallback implements Watcher, AsyncCallback.StatCallback, AsyncCallback.DataCallback {

    private ZooKeeper zk;
    private String path;
    //    private MyConf myConf;
//    private AtomicReference<MyConf> reference;
    private MyConf myConf;

    private CountDownLatch cd = new CountDownLatch(1);

    public WatchCallback(ZooKeeper zk, String path) {
        this.zk = zk;
        this.path = path;
//        this.myConf = myConf;
    }

    public void aWait() {
        zk.exists(path, this, this, "aaa");

        try {
            cd.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("Watch  :: " + event.toString() + "         thread name == " + Thread.currentThread().getName());

        switch (event.getType()) {
            case None:
                break;
            case NodeCreated:
                zk.getData(path, this, this, "ddddd");

                break;
            case NodeDeleted:
                myConf = new MyConf(null);

                cd = new CountDownLatch(1);

                break;
            case NodeDataChanged:
                zk.getData(path, this, this, "ccc");


                break;
            case NodeChildrenChanged:
                break;
            case DataWatchRemoved:
                break;
            case ChildWatchRemoved:
                break;
            case PersistentWatchRemoved:
                break;
        }
    }

    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        System.out.println("exists stat call back stat :: " + stat + "         thread name == " + Thread.currentThread().getName());

        if (stat != null) {
            zk.getData(path, this, this, "bbb");
        } else {
//            try {
//                cd.await();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
    }

    // getData call back
    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        System.out.println("processResult stat call back stat :: " + stat + "         thread name == " + Thread.currentThread().getName());

        if (stat != null) {
            String conf = new String(data);
//            myConf.setConf(conf);
            myConf = new MyConf(conf);

            cd.countDown();
        }

    }

    public MyConf getConf() {
        return myConf;
    }
}
